import utilTool from './utilTool';

const userTool = {
  sign: function (user, realUser, closeTable) {
    let obj = {
      id: user.value.id,
      name: user.value.name,
      password: user.value.password,
    };
    fetch('http://localhost:8080/user/sign', {
      mode: 'cors', //跨域请求
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      body: JSON.stringify(obj),
    })
      .then(response => response.json())
      .then(json => {
        if (json.code == '200') {
          //realUser.value = json.data;
          localStorage.setItem('session', JSON.stringify(json.data));
          this.getUserInfo(realUser, json.data);
          closeTable();
        } else {
          alert(json.msg);
        }
      });
  },
  login: function (user, realUser, closeTable) {
    let obj = {
      id: user.value.id,
      name: user.value.name,
      password: user.value.password,
    };
    fetch('http://localhost:8080/user/login', {
      mode: 'cors', //跨域请求
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      body: JSON.stringify(obj),
    })
      .then(response => response.json())
      .then(json => {
        if (json.code == '200') {
          //realUser.value = json.data;
          localStorage.setItem('session', json.data);
          this.getUserInfo(realUser, json.data);
          closeTable();
        } else {
          alert(json.msg);
        }
      });
  },
  getUserInfo: function (user) {
    let session = localStorage.getItem('session');
    if (utilTool.isNotEmpty(session)) {
      let obj = {
        session: session,
      };
      fetch('http://localhost:8080/user/getUserInfo', {
        mode: 'cors', //跨域请求
        headers: {
          'Content-Type': 'application/json',
        },
        method: 'POST',
        body: JSON.stringify(obj),
      })
        .then(response => response.json())
        .then(json => {
          if (json.code == '200') {
            user.value = json.data;
          } else {
            alert(json.msg);
            localStorage.removeItem('session');
          }
        });
    }
  },
  exit: function (callback) {
    let session = localStorage.getItem('session');
    localStorage.removeItem('session');
    if (session != null && session != undefined && session != '') {
      let obj = {
        session: session,
      };
      fetch('http://localhost:8080/user/exit', {
        mode: 'cors', //跨域请求
        headers: {
          'Content-Type': 'application/json',
        },
        method: 'POST',
        body: JSON.stringify(obj),
      })
        .then(response => response.json())
        .then(json => {
          if (json.code == '200') {
          } else {
            alert(json.msg);
          }
        });
    }
  },
};

export default userTool;
